import { Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
} from '@angular/forms';
import promise from '../../../common/utils/promise';
import { NzModalService } from 'ng-zorro-antd';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login-new',
  templateUrl: './login-new.component.html',
  styleUrls: ['./login-new.component.scss'],
})
export class LoginNewComponent implements OnInit {
  validateForm: FormGroup;


  constructor(private fb: FormBuilder, private modalService: NzModalService, private location: Location, private router: Router) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
    });
  }

  /**
   * 登录
   */
  login(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
      if (this.validateForm.controls[i].errors != null) {
        return;
      }
    }
    // 请求接口
    promise.commonRequest.post({
      username: this.validateForm.value.userName,
      password: this.validateForm.value.password,
    }, '/loginService/getloginData').then(data => {
      console.log(data);
      // @ts-ignore
      if (data.status) {
        this.modalService.success({
          nzTitle: '成功',
          nzContent: '登录成功，正在跳转...',
        });
        // 存储token和username
        sessionStorage.setItem('loginMessage', JSON.stringify(data));
        // 跳转
        let url = sessionStorage.getItem('previousUrl') ? sessionStorage.getItem('previousUrl') : '/dashboard';
        setTimeout(() => {
          this.router.navigateByUrl(url);
        }, 2000);
      } else {
        this.modalService.error({
          nzTitle: '失败',
          // @ts-ignore
          nzContent: data.msg,
        });
      }

    }).catch(error => {
      this.modalService.error({
        nzTitle: '失败',
        nzContent: error.msg,
      });
    });
  }


  /**
   * 验证token
   */
  validateTokenFunc() {
    promise.commonRequest.post(JSON.parse(sessionStorage.getItem('loginMessage')), '/loginService/validateToken').then(data => {
      console.log(data);
    }).catch(error => {
      console.log(error);
    });
  }
}


